/*
 * Copyright 2007-2009 Perttu "celeron55" Ahola <celeron55@gmail.com>
 *
 * This file is part of jukumagic.
 *
 * jukumagic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * jukumagic is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with jukumagic.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"
#include "netcomponent.h"
#include "jukuapp.h"

#include <iostream>

NetComponent::NetComponent()
{
	//std::cout<<"NetComponent"<<std::endl;
}

NetComponent::~NetComponent()
{
	//std::cout<<"~NetComponent"<<std::endl;
}

void NetComponent::WriteXML(TiXmlNode* root)
{
    TiXmlElement *element = new TiXmlElement("NetComponent");
    root->LinkEndChild(element);
    element->SetAttribute("refdes", m_refdes.mb_str(wxConvUTF8));
    element->SetAttribute("value", m_value.mb_str(wxConvUTF8));
    element->SetAttribute("footprint", m_footprint.mb_str(wxConvUTF8));
    element->SetAttribute("device", m_device.mb_str(wxConvUTF8));
	WriteBaseXML(element);
}

JukuObject* NetComponent::ReadFromXMLElement(TiXmlElement* element)
{
    NetComponent *netcomponent = new NetComponent();

	netcomponent->SetRefdes(wxString(element->Attribute("refdes"), wxConvUTF8));
	netcomponent->SetValue(wxString(element->Attribute("value"), wxConvUTF8));
	netcomponent->m_footprint = wxString(element->Attribute("footprint"), wxConvUTF8);
	netcomponent->m_device = wxString(element->Attribute("device"), wxConvUTF8);
	
	netcomponent->ReadBaseXML(element);

    return netcomponent;
}

bool NetComponent::ThrowToBoard(Board *board)
{
	Component *c_already_on_board = board->FindComponent(m_refdes);
	if(c_already_on_board){
		//be sure value is right
		if(c_already_on_board->GetValue() != m_value){
			c_already_on_board->SetValue(m_value);
			std::cout<<"changed value of "<<c_already_on_board->GetRefdes().fn_str()<<std::endl;
		}
		return true;
	}
	if(m_footprint.IsEmpty()){
		std::cout<<m_refdes.fn_str()<<" has empty footprint, not adding"<<std::endl;
		return false;
	}
	Footprint *lf = wxGetApp().m_library.GetFootprint(m_footprint);
	if(lf==NULL){
		std::cout<<"didn't find footprint \""<<m_footprint.fn_str()<<"\""<<std::endl;
		return false;
	}
	
	Footprint *nf = new Footprint(*lf);
	if(nf==NULL) return false;
	Component *c = new Component();
	if(c==NULL){ delete nf; return false; }
	c->SetFootprint(nf);
	c->SetRefdes(m_refdes);
	c->SetValue(m_value);
	board->ThrowComponent(c);
	//m_boardwindow->ThrowComponent(c);

	return true;
}


